'''
Created on Apr 20, 2012

@author: root
'''
from Base import Base
#from Node import Node
import Queue
#import ssh
import threading



class Java(Base):
    
    Nodes = []
    Users = []
    returnQueue = Queue.Queue()
    JDKStatus = []
    openJDKStatus = 0
    remoteInstallPath = "/tmp/pachyderm"
    localJavaPath = ""
    remoteJavaPath = ""
    JDKversion = ""

    
#    localJavaBin = "/tmp"
#    remoteJavaBin = "/tmp"

    def GetJDKVersion(self):
        if (self.localJavaPath==None):
            self.localJavaPath="./software"
        return (self.localJavaPath.split('/'))[len(self.localJavaPath.split('/'))-1]
        
    def CheckJDK(self,output):
        checkStatus = 0 
        endCheckStatus = 0
        threadCount = 0
        Threads = [] 
        self.JDKStatus = []
        if (output): 
            print "    * Checking Java Development Kit Status"

        checkCurrentCMD =  str(self.installSudo) + "rpm -qa |grep jdk"
        for node in self.Nodes:
            Threads.append(threading.Thread(target=self.SSHExec,args=(checkCurrentCMD,node.hostName,self.installUser,self.installPW,True)))
            Threads[threadCount].daemon=True
            Threads[threadCount].start()     
            threadCount = threadCount + 1
        for thread in Threads:
            thread.join()
            (hostName,username,status,results) = self.returnQueue.get()
            jdkDetails = {}
            jdkDetails['hostname'] = ""
            jdkDetails['version'] = ""
            jdkDetails['status'] = 0
            if results:
                if ('openjdk' in results[0]):
                    version = str(results).split("-")[1]
                    jdkDetails['hostname'] = hostName
                    jdkDetails['version'] = "openJDK:"+version
                    jdkDetails['status'] = 1
                    self.JDKStatus.append(jdkDetails) 
                    self.openJDKStatus = 1              
                elif str(results[0]).startswith('jdk') and ('openjdk' not in results[0]):
                    version = str(results).split("-")[1]
                    jdkDetails['hostname'] = hostName
                    jdkDetails['version'] = "Oracle:"+version
                    jdkDetails['status'] = 0
                    self.JDKStatus.append(jdkDetails)
                else:
                    jdkDetails['hostname'] = hostName
                    jdkDetails['version'] = "None"
                    jdkDetails['status'] = 2
                    self.JDKStatus.append(jdkDetails)
            else:
                jdkDetails['hostname'] = hostName
                jdkDetails['version'] = "None"
                jdkDetails['status'] = 2
                self.JDKStatus.append(jdkDetails)

            self.LogInfo("JDK Version "+jdkDetails['hostname']+":"+jdkDetails['version'])
            if (output):print "        * "+jdkDetails['hostname']+":"+jdkDetails['version']

            
        for node in self.Nodes:
            for jdk in self.JDKStatus:
                if (str(node.hostName).upper() in str(jdk['hostname']).upper()):
                    node.javaVersion = jdk['version']
                    checkStatus  = max(checkStatus,jdk['status'])
        return checkStatus

    def VerifyJDK(self):
        print "Add code for md5sum"
        
        
    def PushJDK(self):
        pushStatus = 0
        self.LogInfo("Oracle JDK Push Process Starting....")
        threadCount = 0
        Threads = [] 
        
        for node in self.Nodes:
            for jdk in self.JDKStatus:
                if (jdk['status'] > 0) and (str(node.hostName).upper() == str(jdk['hostname']).upper()):
                
                    Threads.append(threading.Thread(target=self.SSHPut,args=(node.hostName,self.installUser,self.installPW,self.localJavaPath,self.remoteJavaPath,True)))
                    Threads[threadCount].daemon=True
                    Threads[threadCount].start()     
                    threadCount = threadCount + 1
                    if (threadCount==1):
                        self.LogInfo("Push Started:Oracle JDK:"+node.hostName+":"+self.remoteJavaPath)
                        print "    * Pushing Oracle JDK to applicable Cluster Nodes"

        for thread in Threads:
            thread.join()
            (hostName,username,status,results) = self.returnQueue.get()
            if (status == 0):
                    self.LogInfo("Push Completed:Oracle JDK:"+hostName+":"+self.remoteJavaPath)
                    print "        * Oracle JDK push to "+hostName+ " Completed"
            else:
                self.LogError(str(hostName)+" : "+str(results)+" ; Exiting")
                print "        * ERROR Oracle JDK push to "+hostName+ " Failed"

                pushStatus = -1
        if (pushStatus == 0):
            self.LogInfo("Oracle JDK Push Process Completed.")
            return 0
        else:
            return -1

                
    def RemoveOpenJDK(self):
        rmStatus = 0
        self.LogInfo("OpenJDK Removal Process Starting....")

        threadCount = 0
        Threads = [] 
        self.CheckJDK(True)
        if (self.openJDKStatus==1):
#            print "---------------------------------------------------"
#            choice = self.query_yes_no("OpenJDK found on nodes of this cluster. Would you like to remove it?","yes")
#            print "---------------------------------------------------"
            choice = True
            if choice:
                print "    * Removing OpenJDK from applicable Cluster Nodes"
                for node in self.Nodes:
                    for jdk in self.JDKStatus:
                        if (jdk['status'] == 1 ) and (str(node.hostName).upper() == str(jdk['hostname']).upper()):
                            removeCMD = str(self.installSudo) + "rpm -e --nodeps `rpm -qa | grep openjdk`"
        
                            Threads.append(threading.Thread(target=self.SSHExec,args=(removeCMD,node.hostName,self.installUser,self.installPW)))
                            Threads[threadCount].daemon=True
                            Threads[threadCount].start()     
                            threadCount = threadCount + 1
                            self.LogInfo("Removal Started:OpenJDK:"+node.hostName)

                for thread in Threads:
                    thread.join()
                    (hostName,username,status,results) = self.returnQueue.get()
                    if (status == 0):
                        self.LogInfo("Removal Completed:OpenJDK:"+hostName)
                        print "        * OpenJDK successfully removed from "+hostName
                    else:
                        self.LogError(str(hostName)+" : "+str(results)+" ; Exiting")
                        print "        * OpenJDK removal from "+hostName+" failed"

                        rmStatus = -1
            if (self.CheckJDK(False) == 0) and (choice):
                    self.LogError("OpenJDK Removal Process Failed ; Exiting")
                    rmStatus = -1
        if (rmStatus == 0):
            self.LogInfo("OpenJDK Removal Process Completed.")
        else:
            self.LogError("OpenJDK Removal Process Failed ; Exiting")
        return rmStatus
     
    def SetupEnv(self):
      
        envStatus = 0
        threadCount = 0
        Threads = [] 
        self.LogInfo("Setting JAVA_HOME Across Cluster....")
        print "    * Setting JAVA_HOME Variable on all Cluster Nodes"

        for node in self.Nodes:
            envCMD = str(self.installSudo) + "sh -c \"echo 'export JAVA_HOME=/usr/java/latest' > /etc/profile.d/java.sh\""
            Threads.append(threading.Thread(target=self.SSHExec,args=(envCMD,node.hostName,self.installUser,self.installPW)))
            Threads[threadCount].daemon=True
            Threads[threadCount].start()     
            threadCount = threadCount + 1

        for thread in Threads:
            thread.join()
            (hostName,username,status,results) = self.returnQueue.get()
            if (status == 0):
                self.LogInfo("JAVA_HOME set on "+ hostName)
                print "        * JAVA_HOME set on "+hostName
            else:
                self.LogError(str(hostName)+" : "+str(results)+" ; Exiting")
                envStatus = -1
            
        if (envStatus == 0):
            self.LogInfo("JAVA_HOME Setup Completed.")
        else:
            self.LogError("JAVA_HOME Setup Failed ; Exiting")
        return envStatus
                        
            
    def InstallJDK(self):
        installStatus = 0
        threadCount = 0
        Threads = [] 
        output = False
        self.LogInfo("Oracle JDK Installation Process Starting....")

        for node in self.Nodes:
            for jdk in self.JDKStatus:
                if (jdk['status'] > 0  ) and (str(node.hostName).upper() == str(jdk['hostname']).upper()):
                    output = True
                    installCMD = str(self.installSudo) + "rpm -i --nodeps " + self.remoteJavaPath
                    Threads.append(threading.Thread(target=self.SSHExec,args=(installCMD,node.hostName,self.installUser,self.installPW)))
                    Threads[threadCount].daemon=True
                    Threads[threadCount].start()     
                    threadCount = threadCount + 1
                    self.LogInfo("Installation Started:"+self.GetJDKVersion()+":"+node.hostName)
                    if (threadCount==1):
                        print "    * Installing Oracle JDK on applicable Cluster Nodes"

        for thread in Threads:
            thread.join()
            (hostName,username,status,results) = self.returnQueue.get()

            if (status == 0):
                self.LogInfo("Installation Completed:"+self.GetJDKVersion()+":"+hostName)
                print "        * Oracle JDK installed on "+hostName
            else:
                self.LogError(str(hostName)+" : "+str(results)+" ; Exiting")
                print "        * Oracle JDK "+self.GetJDKVersion()+" install failed on "+hostName

                installStatus = -1
            
        if (self.CheckJDK(output) > 0):
                self.LogError("Oracle JDK Installation Process Failed ; Exiting")
                installStatus = -1
        if (installStatus == 0):
            self.LogInfo("Oracle JDK Install Process Completed.")
        else:
            self.LogError("Oracle JDK Installation Process Failed ; Exiting")
            
            
            
      
        
    
        return installStatus
                    

    
    def __init__(self,Nodes,Users,localJavaPath):
        self.Users = Users
        self.Nodes = Nodes
        self.localJavaPath = localJavaPath
        Base.__init__(self)
        self.SetUsers(self.Users)
        
        self.remoteJavaPath = self.remoteInstallPath + "/" + self.GetJDKVersion()
